/**
 * Created by Void on 2017/7/13.
 *
 *  调用手机硬件的类
 *
 * plugins: status splash network
 *
 *
 */

import {Injectable} from '@angular/core';
import {ToastController, LoadingController, Platform, Loading, AlertController} from 'ionic-angular';
import {StatusBar} from "@ionic-native/status-bar";
import {SplashScreen} from "@ionic-native/splash-screen";
import {Network} from '@ionic-native/network';

import {GlobalData} from './GlobalData'

@Injectable()
export class NativeServiceC {
    private loading:Loading;
    private loadingIsOpen:boolean = false;

    constructor(private platform:Platform,
                private toastCtrl:ToastController,
                private alertCrl:AlertController,
                private loadingCtrl:LoadingController,
                private statusBar:StatusBar,
                private splashScreen:SplashScreen,
                private network:Network,
                private globalData:GlobalData) {
    }

    log(info):void {
        console.log('%cNativeService/' + info, 'color:#C41A16');
    }

    statusBarStyleDefault():void {
        this.statusBar.styleDefault();
    }

    splashScreenHide():void {
        this.splashScreen.hide();
    }

    getNetworkType():string {
        if (!this.isMobile()) {
            return 'wifi';
        }
        return this.network.type;
    }

    isConnecting():boolean {
        return this.getNetworkType() != 'none';
    }

    isMobile():boolean {
        return this.platform.is('mobile') && !this.platform.is('mobileweb');
    }

    isAndroid():boolean {
        return this.isMobile() && this.platform.is('android');
    }

    isIos():boolean {
        return this.isMobile() && (this.platform.is('ios') || this.platform.is('ipad') || this.platform.is('iphone'));
    }

    alert(title:string):void {
        this.alertCrl.create({
            title:title,
            buttons:[{text:'确定'}]
        }).present();
    }

    /**
     * 统一调用此方法显示loading
     * @param content 显示的内容
     */
    showLoading(content:string = ''):void {
        if (!this.globalData.showLoading){
            return ;
        }

        if (!this.loadingIsOpen){
            this.loadingIsOpen = true;
            this.loading = this.loadingCtrl.create({
                content:content
            });
            this.loading.present();
            setTimeout(() => { // 最长显示15s
                this.loadingIsOpen && this.loading.dismiss();
                this.loadingIsOpen = false;
            },15000);
        }
    }

    /**
     * 关闭loading
     */
    hideLoading():void {
        if (!this.globalData.showLoading){
            this.globalData.showLoading = true;
        }
        this.loadingIsOpen && this.loading.dismiss();
        this.loadingIsOpen = false;
    }
}